from django.views.generic import TemplateView

from common.mixins import SidebarMixin, PageinatorMixin
from .models import Task


class TaskListView(SidebarMixin, PageinatorMixin, TemplateView):

    template_name = 'task/list.html'
    task_list = None
    as_assignee = True
    section_title = 'Tasks Being Assigned'

    @property
    def search_url(self):
        return 'task:view_list_as_assignee'

    def dispatch(self, request, *args, **kwargs):
        # print(args, kwargs)
        # print(request.path)
        self.per_page = 10
        if 'assignor' in request.path:
            self.as_assignee = False

        return super(TaskListView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        if self.as_assignee:
            self.task_list = Task.objects.filter(assignee=request.user)
        else:
            self.task_list = Task.objects.filter(assignor=request.user)

        return super(TaskListView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(TaskListView, self).get_context_data(**kwargs)

        ttype = self.request.GET.get('ttype')
        if ttype:
            self.task_list = self.task_list.filter(ttype=ttype)

        status = self.request.GET.get('status')
        if status:
            self.task_list = self.task_list.filter(status=status)

        q = self.request.GET.get('q')
        if q:
            context['q'] = q
            valid_ids = []
            for task in self.task_list:
                if q in task.student.username:
                    valid_ids.append(task.id)
            self.task_list = self.task_list.filter(id__in=valid_ids)

        self.task_list = super(TaskListView, self).paging(self.task_list)
        # print('self.task_list', self.task_list)
        context['object_list'] = self.task_list

        return context
